package com.kerong.chedeli.view.home;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;

import com.baidu.location.BDLocation;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.kerong.chedeli.CheDeLiApplication;
import com.kerong.chedeli.R;
import com.kerong.chedeli.adapter.CarListAdapter;
import com.kerong.chedeli.data.modal.CarSimpleListResult;
import com.kerong.chedeli.data.modal.CarSimpleModal;
import com.kerong.chedeli.data.modal.ShopModal;
import com.kerong.chedeli.view.BaseActivity;
import com.kerong.chedeli.view.UIHelper;
import com.kerong.chedeli.view.tenant.CarDetailActivity;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by lyh on 15/10/16.
 */
public class CarListActivity extends BaseActivity {
    private ShopModal shopModal;
    private List<CarSimpleModal> itemList;
    private CarListAdapter carListAdapter;
    @Bind(R.id.grid_view)
    PullToRefreshGridView gridView;
    private int currentPage=1;
    private boolean needRefresh = true;//判断是否需要刷新

    @Bind(R.id.no_date_layout)
    RelativeLayout nodate_layout;

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_carlist);
        ButterKnife.bind(this);
        initToolBar(toolbar);
        shopModal = getIntent().getParcelableExtra("shop");
        init();
    }

    private void init(){
        itemList = new ArrayList<CarSimpleModal>();
        carListAdapter = new CarListAdapter(this,itemList);
        gridView.setAdapter(carListAdapter);
        gridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                initViewData(1);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                if (needRefresh) {
                    initViewData(currentPage);
                }
            }
        });
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CarSimpleModal carSimpleModal = itemList.get(position);
                Intent intent = new Intent();
                intent.putExtra("carModal",carSimpleModal);
                turnToActivity(CarDetailActivity.class,intent);
            }
        });
        //首页进来没数据进行初始化加载
        if(itemList.isEmpty()){
                initViewData(1);
        }
    }

    private void initViewData(final int page)
    {

            FinalHttp finalHttp = new FinalHttp();
            String url = "http://cdlmapi.0371e.cn/v1/carsearch";
            AjaxParams ajaxParams = new AjaxParams();
            BDLocation location = CheDeLiApplication.location;
            ajaxParams.put("region", location.getCity());
            ajaxParams.put("nearby","0");
            ajaxParams.put("lat",location.getLatitude()+"");
            ajaxParams.put("lng",location.getLongitude()+"");
            ajaxParams.put("leaseprice","");
            ajaxParams.put("gearbox","1");
            ajaxParams.put("brandid","");
            ajaxParams.put("carmodel","");
            ajaxParams.put("carage","");
            ajaxParams.put("seat", "");
            ajaxParams.put("cartype","");
            ajaxParams.put("carcfg","");
            ajaxParams.put("displacement","");
            ajaxParams.put("carcolor","");
            ajaxParams.put("shopid",shopModal.getShopid());
            //ajaxParams.put("shopid","");
            ajaxParams.put("pagesize",CheDeLiApplication.PAGE_SIZE+"");
            ajaxParams.put("pagenum",page+"");
            finalHttp.get(url, ajaxParams, new AjaxCallBack<String>() {
                @Override
                public void onSuccess(String s) {
                    try {
                        CarSimpleListResult carSimpleListResult = new Gson().fromJson(s,CarSimpleListResult.class);
                        if(carSimpleListResult.getTotal()==0){
                            needRefresh = false;
                        }else{
                            needRefresh = true;
                        }
                        if(page==1){
                            if(carSimpleListResult.getResults().size()==0){
                                nodate_layout.setVisibility(View.VISIBLE);
                            }
                            itemList.clear();
                            itemList.addAll(carSimpleListResult.getResults());
                        }else{
                            itemList.addAll(carSimpleListResult.getResults());
                        }
                        currentPage++;
                    }catch (Exception e){
                        UIHelper.showMessage(e.getMessage());
                    }
                    carListAdapter.notifyDataSetChanged();
                    gridView.onRefreshComplete();
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    UIHelper.showMessage("数据加载失败，请联系管理员");
                }
            });

        }
}
